package com.rem.service.impl;

import com.rem.dao.BookDao;
import com.rem.dao.impl.BaseDao;
import com.rem.dao.impl.BookDaoImpl;
import com.rem.pojo.Book;
import com.rem.pojo.Page;
import com.rem.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();

    public int addBook(Book book) {
        return bookDao.addBook(book);
    }

    public int deleteBookById(Integer id) {
        return bookDao.deleteBookById(id);

    }

    public int updateBook(Book book) {
        return bookDao.updateBook(book);
    }

    public Book queryBookById(Integer id) {
        return bookDao.queryBookById(id);
    }

    public List<Book> queryBooks() {
        return bookDao.queryBooks();
    }

    public Integer queryForPageTotalCount() {
        return bookDao.queryForPageTotalCount();
    }

    public List<Book> queryForPageItems(int begin, int pageSize) {

        return bookDao.queryForPageItems(begin,pageSize);
    }

    public Integer queryForPageTotalCountByPrice(int min, int max) {
        return bookDao.queryForPageTotalCountByPrice(min,max);
    }

    @Override
    public List<Book> queryForPageItemsByPrice(int begin, int pageSize, int min, int max) {
        return bookDao.queryForPageItemsByPrice(begin,pageSize,min,max);
    }

    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page = new Page<>();
        
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);

        Integer pageTotalCount = bookDao.queryForPageTotalCount();
        page.setPageTotalCount(pageTotalCount);

        int PageTotal = pageTotalCount/pageSize;
        if (pageTotalCount % pageSize > 0){
            PageTotal++;
        }
        page.setPageTotal(PageTotal);

        // 求当前页数据的开始索引
        int begin = (page.getPageNo() - 1) * pageSize;
        // 求当前页数据
        List<Book> items = bookDao.queryForPageItems(begin,pageSize);
        // 设置当前页数据
        page.setItems(items);

        return page;
    }

    @Override
    public Page<Book> pageByPrice(Integer pageNo, int pageSize, Integer minPrice, Integer maxPrice) {
        Page<Book> page = new Page<>();

        page.setPageNo(pageNo);
        page.setPageSize(pageSize);

        Integer pageTotalCount = bookDao.queryForPageTotalCountByPrice(minPrice,maxPrice);
        page.setPageTotalCount(pageTotalCount);

        int PageTotal = pageTotalCount/pageSize;
        if (pageTotalCount % pageSize > 0){
            PageTotal++;
        }
        page.setPageTotal(PageTotal);

        // 求当前页数据的开始索引
        int begin = (page.getPageNo() - 1) * pageSize;
        // 求当前页数据
        List<Book> items = bookDao.queryForPageItemsByPrice(begin,pageSize,minPrice,maxPrice);
        // 设置当前页数据
        page.setItems(items);

        return page;
    }
}
